<template>
  <div class="app-container">
    <div class="filter-container">
      <p style="float:left;margin-top:5px;margin-left:2%">商品标题：</p>
      <el-input
        v-model="listQuery.title"
        size="small"
        placeholder="请输入商品标题"
        style="width: 200px;float:left"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select
        size="small"
        placeholder="请选择渠道"
        clearable
        class="filter-item"
        style="width: 250px;margin-left:2%"
        v-model="listQuery.channelType"
      >
        <el-option
          v-for="item in calendarTypeOptions"
          :key="item.key"
          :label="item.display_name"
          :value="item.key"
        />
      </el-select>
      <el-button
        size="small"
        class="filter-item"
        type="success"
        icon="el-icon-search"
        style="margin-left:3%"
        @click="handleFilter"
      >搜索</el-button>
      <el-button
        size="small"
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >添加</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      size="small"
      border
      fit
      highlight-current-row
      style="width: 100%;margin-top:1%"
    >
      <el-table-column label="商品" min-width="250px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.infoName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" width="200px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="渠道" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.channelType=='APPLETS'?'小程序':scope.row.channelType=='CUSTOMER_APP'?'C端APP':scope.row.channelType=='SHOP_KEEPER'?'掌柜APP':scope.row.channelType=='OPERATE'?'运营管理平台':'' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片" width="300px" align="center">
        <template slot-scope="scope">
          <!-- <span>{{ scope.row.phoneNumber }}</span> -->
          <img :src="scope.row.imgUrl" style="width:300px;height:100px" alt />
        </template>
      </el-table-column>
      <el-table-column label="排序" width="300px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.orders }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="200px"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button size="small" align="center" type="danger" @click="handledelete(row)">删除</el-button>
          <el-button size="small" align="center" type="primary" @click="handleUpdate(row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
    <el-dialog
      :close-on-click-modal="false"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      append-to-body
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="150px"
        style="width: 700px; margin-left:50px;"
      >
        <el-form-item label="商品ID：">
          <v-selectpage :data="sample" key-field="proId" v-model="temp.proId" show-field="infoName"></v-selectpage>
        </el-form-item>
        <el-form-item label="商品标题：">
          <el-input v-model="temp.title" />
        </el-form-item>

        <el-form-item label="地址">
          <el-cascader :options="areaData" size="small" ref="area" :props="{value: 'code', label: 'name'}" @change="areaChange" style="width:400px"></el-cascader>
        </el-form-item>

        <el-form-item label="图片路径：">
          <el-input v-model="temp.imgUrl" />
        </el-form-item>
        <el-form-item label="渠道">
          <el-select
            size="small"
            placeholder="请选择渠道"
            clearable
            class="filter-item"
            style="width: 250px;margin-left:2%"
            v-model="temp.channelType"
          >
            <el-option
              v-for="item in calendarTypeOptions"
              :key="item.key"
              :label="item.display_name"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label>
          <el-upload
            class="avatar-uploader"
            action="http://10.0.0.123:10001/uploadImgUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :http-request="customRequest"
          >
            <img
              style="width:100px;height:100px"
              v-if="temp.imgUrl"
              :src="temp.imgUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="排序：">
          <el-input v-model="temp.orders" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">返回</el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { updateManu, createManufacturer, batchDel } from "@/api/manufacturer"; // 异步请求 delLly
import Vue from "vue";
import {
  getListPage,
  delHeadWheel,
  addImg,
  getAllProInfo,
  updateHead,
  addHead
} from "@/api/headWheel";
import { parseTime } from "@/utils";
import areaData from "@/utils/area_data";
import Pagination from "@/components/Pagination"; // 分页插件
import { SelectPage } from "v-selectpage";

const calendarTypeOptions = [
  { key: "APPLETS", display_name: "小程序" },
  { key: "CUSTOMER_APP", display_name: "C端APP" },
  { key: "SHOP_KEEPER", display_name: "掌柜APP" },
  { key: "OPERATE", display_name: "运营管理平台" }
];
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name;
  return acc;
}, {});

export default {
  inject: ["reload"],
  components: { Pagination, "v-selectpage": SelectPage },

  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "info",
        deleted: "danger"
      };
      return statusMap[status];
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type];
    }
  },
  data() {
    return {
      sample: [],
      deptValue: "",
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        title: "",
        sort: "+id",
        channelType: ""
      },
      deps: [],
      sortOptions: [
        { label: "ID Ascending", key: "+id" },
        { label: "ID Descending", key: "-id" }
      ],
      statusOptions: ["published", "draft", "deleted"],
      showReviewer: false,
      temp: {
        id: undefined,
        imgUrl: "",
        proId_text: ""
      },
      dialogFormVisible: false,
      calendarTypeOptions,
      dialogStatus: "",
      textMap: {
        update: "查看详情",
        create: "添加"
      },
      rowId: "",
      dialogPvVisible: false,
      outerVisible: false,
      pvData: [],
      rules: {
        type: [
          { required: true, message: "type is required", trigger: "change" }
        ],
        timestamp: [
          {
            type: "date",
            required: true,
            message: "timestamp is required",
            trigger: "change"
          }
        ],
        title: [
          { required: true, message: "title is required", trigger: "blur" }
        ]
      },
      downloadLoading: false,
      liaUser: null,
      ids: [],
      select: null,
      allInfo: [],
      areaData: areaData
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getAllInfo() {
      getAllProInfo().then(res => {
        console.log(res.data);
        this.sample = res.data;
      });
    },

    
    areaChange(value){
      console.log(value)
      console.log(this.$refs['area'].getCheckedNodes())
    },
    handleAvatarSuccess(res, file) {
      this.temp.imgUrl = URL.createObjectURL(file.raw);
    },
    customRequest(data) {
      const formData = new FormData();
      formData.append("file", data.file);
      this.saveFile(formData);
    },
    saveFile(formData) {
      addImg(formData).then(res => {
        // this.imageUrl=res.data
        this.temp.imgUrl = res.data.filePath;
        console.log(this.temp.imgUrl);
      });
    },
    getList() {
      this.listLoading = true;
      var params = {
        // pageConvert: true,
        pageNum: this.listQuery.pageNum,
        pageSize: this.listQuery.pageSize,
        // realName:this.listQuery.realName,
        // phoneNumber:this.listQuery.phoneNumber
        title: this.listQuery.title,
        channelType: this.listQuery.channelType
      };
      getListPage(params).then(response => {
        this.list = response.data;
        console.log(this.list);
        this.total = response.recordsTotal;
        console.log(this.total);
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false;
        }, 800);
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: "操作成功",
        type: "success"
      });
      row.status = status;
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.handleFilter();
    },
    resetTemp() {
      this.temp = {
        id: undefined
      };
    },
    handleUpdate(row) {
      this.getAllInfo();
      this.temp = Object.assign({}, row); // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      const tempData = Object.assign({}, this.temp);
      console.log(tempData);
      updateHead(tempData).then(() => {
        for (const v of this.list) {
          if (v.id === this.temp.id) {
            const index = this.list.indexOf(v);
            this.list.splice(index, 1, this.temp);
            break;
          }
        }
        this.dialogFormVisible = false;
        this.$notify({
          title: "成功",
          message: "修改成功",
          type: "success",
          duration: 2000
        });
      });
      this.reload();
    },
    handleCreate() {
      this.getAllInfo();
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    createData() {
      console.log(this.temp.infoName);
      addHead(this.temp).then(() => {
        this.list.unshift(this.temp);
        this.dialogFormVisible = false;
        this.$notify({
          title: "成功",
          message: "添加成功",
          type: "success",
          duration: 2000
        });
        this.reload();
      });
    },
    handledelete(row) {
      this.rowId = row.id;
      this.$confirm("确定删除？ 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      })
        .then(() => {
          delHeadWheel(this.rowId).then(res => {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.reload();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort;
      return sort === `+${key}`
        ? "ascending"
        : sort === `-${key}`
        ? "descending"
        : "";
    }
  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
